<template>
  <div class="page no-follow-config">
    <div>
      <div style="padding-bottom: 50px;">
        <group v-if="init" class="" title="此规则针对所有顾问（特殊顾问除外）">
          <cell title="禁止前顾问再次抢该客户天数限制" text-align="right"
          :value="distributeLimit.forbid_grab_day" is-link
          @click.native="config('forbid_grab_day', distributeLimit, 'unify')">
          </cell>
        </group>
        <group title="可以单独设置特殊前顾问的抢客户规则，不设置则所有顾问按照统一规则执行"></group>
        <group title="已设置"></group>
        <group class="clearfix" v-for="(data, index) in distributeLimit.data">
          <div class="weui-cells__title" slot="after-title">
            <div class='clearfix'>
              <span class='pull-right' @click="$deleteCounselorDistributeLimit(data, index)">删除</span>
            </div>
          </div>
          <cell title="顾问" :value="data.name"></cell>
          <cell title="禁止前顾问再次抢该客户天数限制" :value="data.forbid_grab_day"
          @click.native="config('forbid_grab_day', data, '$saveCounselorDistributeLimit')" is-link>
          </cell>
        </group>
        <group title="新增(信息填写完整后，新增特殊顾问才可以点击)">
          <cell title="顾问" v-if="freshDistributeLimit.name" :value="freshDistributeLimit.name" is-link
          @click.native="showTeam = true"></cell>
          <cell title="顾问" v-else value="选择营销顾问" is-link
          @click.native="showTeam = true" ></cell>
          <cell title="禁止前顾问再次抢该客户天数限制" :value="freshDistributeLimit.forbid_grab_day"
          v-if="freshDistributeLimit.forbid_grab_day" is-link
          @click.native="config('forbid_grab_day', freshDistributeLimit, false)"></cell>
          <cell title="禁止前顾问再次抢该客户天数限制" v-if="!freshDistributeLimit.forbid_grab_day" value="设置" is-link
          @click.native="config('forbid_grab_day', freshDistributeLimit, false)"></cell>
        </group>
        <button v-if="freshDistributeLimit.suid && freshDistributeLimit.forbid_grab_day" class="btn scrm-default-btn mgt-15"
        @click="addCounselorDistributeLimit(freshDistributeLimit)">+新增特殊顾问</button>
        <button v-else class="btn scrm-default-btn mgt-15" disabled="disabled">+新增特殊顾问</button>
      </div>
    </div>
    <popup v-model="showPopup" class="configPopup">
      <group title="设置天数大约1且不能超过90天">
        <x-input :min="1" :max="2" type="number" title="设置天数" v-model="fieldVal" placeholder="请输入天数">
          <span class="prmiary-btn" slot="right" type="primary" mini @click="finish">保存</span>
          <span class="prmiary-btn darker" slot="right" type="primary" mini @click="cancel()">取消</span>
        </x-input>
      </group>
    </popup>
    <popup v-model="showTeam" height="100%" @touchstart.prevent style="background-color:white;">
      <div v-if="showTeam === true" style="background-color:white;height:100%;">
        <div :class="{'none':!teamsMembers.length}" ref="team_scroller" :noDataText="tnoDataText">
          <team-member-item @on-click="selectMember" v-for="(teamMemberItem, index) in teamsMembers" :key="index"
            :client="teamMemberItem" v-if="existsSuids.indexOf(teamMemberItem.suid) === -1 "></team-member-item>
        </div>
      </div>
      <button class="fixed-bt-btn fixed-btr0-btn" v-if="showTeam === true" @click="showTeam=false">取消</button>
    </popup>
    <confirm v-model="selectConfirm"
        title="温馨提示"
        @on-confirm="selectResolve && selectResolve()">
      <p style="text-align:center;">你确定要选择该顾问?</p>
    </confirm>
    <confirm v-model="deleteConfirm"
        title="温馨提示"
        @on-confirm="deleteResolve && deleteResolve()">
      <p style="text-align:center;">你确定要删除此规则?</p>
    </confirm>
  </div>
</template>
<script>
  import teamMemberItem from '../components/team-member-item'

  import Panel from 'vux/src/components/panel'
  import Group from 'vux/src/components/group'
  import Cell from 'vux/src/components/cell'
  import Radio from 'vux/src/components/radio'
  import Popup from 'vux/src/components/popup'
  import XInput from 'vux/src/components/x-input'
  import XButton from 'vux/src/components/x-button'
  import Confirm from 'vux/src/components/confirm'

  import { mapActions, mapState } from 'vuex'
  import Q from 'q'

  export default {
    methods: {
      initDistributeConfig () {
        return Q.Promise((resolve, reject) => {
          this.getDistributeLimit(this.teamId).then((response) => {
            console.log(response.data.errcode, 'response.data.errcode')
            if (response.data.errcode === 0) {
              this.distributeLimit = response.data.results
              if (this.distributeLimit.data) {
                this.distributeLimit.data.forEach((elem, index) => {
                  this.existsSuids.push(elem.suid)
                })
              }
            }
            this.init = true
            resolve()
          }).catch(() => {
            this.init = true
            resolve()
          })
        })
      },
      // 索引团队成员信息
      indexingDingUser () {
        return Q.Promise((resolve, reject) => {
          this.getTeam(this.teamId).then((response) => {
            if (response.data.errcode === 0) {
              const team = response.data.results
              team.team_members.forEach((element) => {
                this.dingUserSuids[element.ding_user_id] = element.suid
              })
              this.teamsMembers = team.team_members
            }
            resolve()
          }).catch(() => {
            resolve()
          })
        })
      },
      // 设置客户再分配统一规则
      unify () {
        this.$vux.loading.show({text: '保存中...'})
        setTimeout(() => { this.$vux.loading.hide() }, 5000)
        return Q.Promise((resolve, reject) => {
          this.distributeLimit.team_id = this.teamId
          this.saveDistributeLimit(this.distributeLimit).then((response) => {
            this.$vux.loading.hide()
            resolve()
          }).catch(() => {
            this.$vux.loading.hide()
            resolve()
          })
        })
      },
      // 设置客户再分配特殊顾问规则
      $saveCounselorDistributeLimit (distributeConfig) {
        const counselorDistributeConfig = distributeConfig || this.variable
        this.$vux.loading.show({text: '保存中...'})
        setTimeout(() => { this.$vux.loading.hide() }, 5000)
        return Q.Promise((resolve, reject) => {
          counselorDistributeConfig.team_id = this.teamId
          this.saveCounselorDistributeLimit(counselorDistributeConfig).then((response) => {
            this.$vux.loading.hide()
            resolve()
          }).catch(() => {
            this.$vux.loading.hide()
            resolve()
          })
        })
      },
      // 添加客户再分配特殊顾问规则
      addCounselorDistributeLimit (distributeConfig) {
        this.$saveCounselorDistributeLimit(distributeConfig).then(() => {
          this.distributeLimit.data.push(distributeConfig)
          this.freshDistributeLimit = {}
        })
      },
      // 删除客户再分配特殊顾问规则
      $deleteCounselorDistributeLimit (counselorDistributeConfig, index) {
        return Q.Promise((resolve, reject) => {
          this.deleteResolve = resolve
          this.deleteConfirm = true
        }).then(() => {
          this.$vux.loading.show({text: '删除中...'})
          setTimeout(() => { this.$vux.loading.hide() }, 5000)
          counselorDistributeConfig.team_id = this.teamId
          this.deleteCounselorDistributeLimit(counselorDistributeConfig)
          .then((response) => {
            this.distributeLimit.data.splice(index, 1)
            this.$vux.loading.hide()
          }).catch(() => {
            this.$vux.loading.hide()
          })
        })
      },
      config (field, variable, method) {
        this.showPopup = true
        this.field = field
        this.method = method
        this.variable = variable
        this.fieldVal = variable[field]
        if (!this.variable[this.field + '_origin']) {
          this.variable[this.field + '_origin'] = this.variable[this.field]
        }
      },
      cancel () {
        this.variable[this.field] = this.variable[this.field + '_origin']
        this.variable[this.field + '_origin'] = null
        this.showPopup = false
      },
      finish () {
        this.showPopup = false
        if (typeof this[this.method] === 'function') {
          this[this.method]()
        }
      },
      selectMember (member) {
        return Q.Promise((resolve, reject) => {
          this.selectResolve = resolve
          this.selectConfirm = true
        }).then(() => {
          this.freshDistributeLimit.name = member.name
          this.freshDistributeLimit.suid = member.suid
          this.showTeam = false
        })
      },
      initialize () {
        this.$vux.loading.show({text: 'loading'})
        this.initDistributeConfig()
        .then(this.indexingDingUser)
        .then(() => {
          this.loading.hide()
        }).catch(() => {
          this.$vux.loading.hide()
        })
      },
      ...mapActions({
        'getDistributeLimit': 'getDistributeLimit',
        'saveDistributeLimit': 'saveDistributeLimit',
        'getTeam': 'getTeam',
        'saveCounselorDistributeLimit': 'saveCounselorDistributeLimit',
        'deleteCounselorDistributeLimit': 'deleteCounselorDistributeLimit'
      })
    },
    computed: {
      ...mapState({
        team: state => state.app.user.teams ? state.app.user.teams[0] : []
      })
    },
    watch: {
      fieldVal (value) {
        if (this.field) {
          this.variable[this.field] = (value > 90 ? 90 : value) || 1
        }
      },
      team () {
        // if (!this.init) this.initialize()
      }
    },
    components: {
      Group,
      Cell,
      Radio,
      Popup,
      XInput,
      XButton,
      Panel,
      Confirm,
      teamMemberItem
    },
    mounted () {
      this.teamId = this.$route.query.team_id
      // if (this.team && this.teamId) {
      this.initialize()
      // }
      this.callJsApi('biz.navigation.setTitle', {title: '客户再分配设置'})
    },
    data () {
      return {
        team_id: '',
        fieldVal: null,
        showPopup: false,
        field: null,
        variable: null,
        deleteConfirm: false,
        deleteResolve: null,
        selectConfirm: false,
        showTeam: false,
        tnoDataText: '暂无成员',
        method: null,
        dingUserSuids: {},
        existsSuids: [],
        teamsMembers: [],
        distributeLimit: {},
        freshDistributeLimit: {},
        init: false
      }
    }
  }
</script>
<style lang="less">
  @import '../less/base';
</style>
